<?php


namespace app\api\controller;


use app\BaseController;
use app\common\params\common\TokenParams;
use app\service\TokenService;
use think\response\Json;

class Token extends BaseController
{
    private $key = 'zhaocaimao';
    private $password = 'fU9wboOsRx9JQDA2';
    private $version = '8.8.8';

    /**
     * 缓存KEY
     */
    const CACHE_KEY = "TOKEN_";
    const TOKEN_KEY = 'access_token';

    /**
     * 客户端获取access_token
     * @return Json
     */
    public function getAccessToken()
    {
        //参数校验
        $account = input('account');
        if ($account === 'NULL' || empty($account)) {
           return $this->error('app account is require','','100100');
        }
        $password = input('password');
        if ($password === 'NULL' || empty($password)) {
            return $this->error('app password is require','','100101');
        }
        //验证账号密码
        if ($account == $this -> key && $password == $this -> password) {
            $token = $this->createGuid(true);
            //缓存2小时10分钟
            //(new RedisClusterBase())->set(self::CACHE_KEY.$token,$token,7500);
            // return apiReturn(['code'=>200,'data'=>['access_token'=>$token,'expires_in'=>7200]]);
            $t = time();
            $expiration_time_add = 7200000;
            $tokenService = new TokenService();
            $data = [
                'app_token' => $token,
                'update_time' => $t,
                'expiration_time' => $t + $expiration_time_add,
                'login_ip' => ''
            ];
            $where = [
                'account' => $account,
                'password' => $password,
            ];
            //$tokenService -> insertToken($data); //token 两个小时过期，首次数据上线时数据插入表即可，所以不用调用插入方法
            $tokenService -> updateToken($where,$data);
            $result = $this->success('success', ['access_token' => $token, 'expires_in' => $expiration_time_add]);
            return $result;
        } else {
            $result = $this->error('Your account name or password is incorrect.','','1001003');
            return $result;
        }
    }

    /**
     * 生成guid
     * @param $cut 是否删除中杠
     * @return string
     */
    private function createGuid($cut = false) : string
    {
        $charid = strtoupper(md5(uniqid(mt_rand(), true)));
        $hyphen = chr(45);// "-"
        $uuid = ''
            . substr($charid, 0, 8) . $hyphen
            . substr($charid, 8, 4) . $hyphen
            . substr($charid, 12, 4) . $hyphen
            . substr($charid, 16, 4) . $hyphen
            . substr($charid, 20, 12);
        if ($cut) {
            return str_replace('-', '', strtolower($uuid));
        }
        return strtolower($uuid);
    }
}